package com.letu.core.utils;

import cn.hutool.core.util.StrUtil;
import com.letu.core.exception.BizException;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassNameWordUtil
 * @Description 套打word模板
 * @Authoradmin
 * @Date 2022/12/16 15:53
 * @Version 1.0
 **/
public final class WordUtil {

    /**
     * 模版套打生成文件.
     *
     * @param templateUrl    模版地址url
     * @param replacementMap 占位符与值
     * @param docName        文件名
     * @return the file
     * @throws IOException         the io exception
     * @throws XDocReportException the x doc report exception
     */
    public static File createFileByTemplate(String templateUrl, Map<String,Object> replacementMap, String docName) throws IOException, XDocReportException {
        // 模版原始扩展名
        String suffix = templateUrl.lastIndexOf(".") == -1 ? templateUrl: templateUrl.substring(templateUrl.lastIndexOf("."));
        if (StrUtil.isBlank(suffix)) {
            throw BizException.wrap(-1, "模版非法，文件格式缺失");
        }
        // 下载模版文件
        URL url = new URL(templateUrl);
        URLConnection conn = url.openConnection();
        IXDocReport report;
        try (InputStream inStream = conn.getInputStream()) {
            // 注册IXDocReport实例并加载FreeMarker模板引擎
            report = XDocReportRegistry.getRegistry().loadReport(inStream, TemplateEngineKind.Freemarker);
        }
        // 创建IXDocReport上下文对象
        IContext context = report.createContext();
        // 填充占位符
        context.putMap(replacementMap);
        File tempFile = File.createTempFile(docName, suffix);
        try (OutputStream out = Files.newOutputStream(tempFile.toPath())) {
            // 模版套打，生成文件
            report.process(context, out);
        }
        return tempFile;
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("contractNumber","1234");
        map.put("cutomerName","1234");
        map.put("address","1234");
        map.put("uscc","1234");
        map.put("faxNo","1234");
        createFileByTemplate("http://10.20.16.78:9090/pvenue/WJ518449551988654080.docx", map, "测试合同");
    }

}
